package com.fadadianqi.logistics.search;

import com.fadadianqi.search.AbstractSearcher;
import com.fadadianqi.search.Argument;
import com.fadadianqi.search.IndexPathHelper;
import com.fadadianqi.search.IndexPathHelper.IndexEnum;
import com.fadadianqi.logistics.sell.model.Bill;
import com.fadadianqi.logistics.sell.service.BillService;
import com.yeqiangwei.commons.util.Pagination;
import com.yeqiangwei.commons.util.StringHelper;
import com.yeqiangwei.commons.util.Utils;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.highlight.Highlighter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service("sellSearcher")
public class SellSearcher extends AbstractSearcher {

    private IndexPathHelper indexPathHelper = new IndexPathHelper(IndexEnum.SELL);

    @Override
    protected Argument initializtionArgument(String keywords,
                                             Pagination pagination) {
        Argument argument = Argument.getInstance();
        argument.setPagination(pagination);
        argument.setArgs(SellIndexService.FIELD_DETAILS, keywords, Occur.SHOULD, 0.9F);
        argument.setArgs(SellIndexService.FIELD_CUSTOMER_NAME, keywords, Occur.SHOULD, 0.7F);
        argument.setArgs(SellIndexService.FIELD_VILLAGE_NAME, keywords, Occur.SHOULD, 0.5F);
        argument.setArgs(SellIndexService.FIELD_TOWN_NAME, keywords, Occur.SHOULD, 0.5F);

        if (!Utils.isLetter(keywords)) {
            String pinyin = StringHelper.toPinyin(keywords);
            argument.setArgs(SellIndexService.FIELD_DETAILS, pinyin, Occur.SHOULD, 0.9F);
            argument.setArgs(SellIndexService.FIELD_CUSTOMER_NAME, pinyin, Occur.SHOULD, 0.7F);
            argument.setArgs(SellIndexService.FIELD_VILLAGE_NAME, pinyin, Occur.SHOULD, 0.5F);
            argument.setArgs(SellIndexService.FIELD_TOWN_NAME, pinyin, Occur.SHOULD, 0.5F);
        }
        return argument;
    }

    @Override
    protected Object documentToVO(IndexSearcher searcher, Document doc,
                                  Highlighter highlighter) throws IOException {
        String billId = doc.get(Bill.PROP_ID);
        Bill bill = billService.getById(billId);
        return bill;
    }

    @Override
    protected String getIndexPath() {
        return indexPathHelper.getIndexPath();
    }

    @Autowired
    private BillService billService;

}
